#!/usr/bin/env python

"""
MythBoxLink - http://mythboxlink.googlecode.com
(c) 2011 Jared Sutton <jpsutton@gmail.com>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2 as 
published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

import re, os, os.path, commands
import MythBoxLinkUtils as utils
from LocalTVDB import LocalTVDB
from MythBoxLinkSettings import settings
from xbmc.xbmcclient import XBMCClient

def main ():
  # 0. Create stats counters
  matchCounter = dict()
  
  # 1. Clean up broken symlinks (deleted recordings) and build list of already-indexed stuff
  currentLinks = utils.getCurrentLinks(settings.outputDir)

  # 2. Get list of recordings from the MythTV database
  (movieRows, episodeRows) = utils.getRecordingsFromMythDB(currentLinks)

  # 3. Link any movies not already linked
  utils.linkMovies(movieRows)

  # 4. Create our LocalTVDB object
  localTVDB = LocalTVDB()

  # 5. Examine all episode recordings
  for episode in episodeRows:
    if episode[5] == "Default":
      subdir = "recordings"
    elif episode[5] == "LiveTV":
      subdir = "livetv"

    searchTitle = episode[1] if episode[1] not in settings.titleExceptionList else settings.titleExceptionList[episode[1]]
    srcFile = os.path.join(settings.recordingsDir, subdir, episode[3])
    destFolder = os.path.join(settings.outputDir, "TV", searchTitle)
    epData = (episode[4], searchTitle, episode[2], episode[8])

    if not localTVDB.getEpisodeData(searchTitle):
      print("problem with: %s" % str(epData))
      continue

    destFile = None

    # The ordering of this list determines which matching functions are tried first    
    matchingFunctions = [
      (localTVDB.searchByAbsEpNum, "Absolute Number", "a"),
      (localTVDB.searchByAirDateAndSubtitle, "Original Airdate", "d"),
      (localTVDB.searchBySubtitle, "Closest Subtitle", "s"),
    ]

    for (function, desc, ext) in matchingFunctions:
      destFile = function(epData)

      if destFile is not None:
        if desc not in matchCounter:
          matchCounter[desc] = 0

        if settings.debug: 
          print "Matched %s by %s" % (str(epData), desc)

        matchCounter[desc] += 1
        destFile += ".%s.m2ts" % ext
        break

    if destFile is None:
      if "none" not in matchCounter:
        matchCounter["none"] = 0

      destFile = (os.path.join(destFolder, '%s - %s%s' % (searchTitle, episode[2],'.m2ts'))).encode('utf-8')
      matchCounter["none"] += 1

    destFile = os.path.join(destFolder, destFile)
    utils.mkdir(destFolder)
    utils.symlink(srcFile, destFile)
    #fps = utils.getFrameRate(srcFile)
    #utils.generateCommSkipFile(episode[6], episode[7], destFile, fps)

  # 6. Clean up
  localTVDB.deleteEpisodeDB()

  # 7. Print out some pretty stats
  for key in matchCounter.keys():
    print "%d episodes matched by %s" % (matchCounter[key], key)

  # 8. Tell XBMC to update it's video library
  xbmcClient = XBMCClient()
  xbmcClient.connect(settings.XBMCAddress)
  xbmcClient.send_action("UpdateLibrary(video)")

if __name__ == "__main__":
    main()
